import storage from '@/utils/storage'
// import { getQueryVariable } from '@/utils/index'
const APP_NAME = process.env.VUE_APP_NAME
const KEY_USERINFO = APP_NAME ? `userInfo_${APP_NAME}` : 'userInfo'

export function setUserInfo(value) {
  userInfoCache = value
  storage.set(KEY_USERINFO, value)
}

export function getUserInfo() {
  const cache = storage.get(KEY_USERINFO)
  try {
    return JSON.parse(cache)
  } catch (e) {
    return {}
  }
}

export let userInfoCache = getUserInfo()

export function getMenu() {
  return userInfoCache && userInfoCache.functionTreeList
}
function _getMenuByID(menus, id) {
  if (Array.isArray(menus)) {
    for (let i = 0, len = menus.length; i < len; i++) {
      if (menus[i]["id"] === id) {
        return menus[i]
      }
    }
  }
  return null
}
export function getMenuByIDList(ids) {
  if (!userInfoCache && userInfoCache.functionTreeList) {
    return null
  }
  return [].concat(ids).reduce((data, id) => {
    if (!data) {
      return null
    }
    if (Array.isArray(data)) {
      return _getMenuByID(data, id)
    } else if (data.hasOwnProperty('children')) {
      return _getMenuByID(data.children, id)
    } else {
      return null
    }
  }, userInfoCache && userInfoCache.functionTreeList)
}

// 获取地址栏token值
const getQueryString = (name) => {
  var reg = new RegExp("(^|&|\\?)" + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.href.match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

// 退出
export function winOut() {
  try {
    window.opener = window
    var win = window.open("", "_self")
    win.close()
    top.close()
  } catch (e) {
    console.log("TCL: logout -> e", e)
  }
}

export function getToken() {
  const local_token = (JSON.parse(storage.get(KEY_USERINFO)) || {}).token
  const token = getQueryString('access_token') || local_token
  return token
}

export function getWebsiteId() {
  const local_websiteId = (JSON.parse(storage.get(KEY_USERINFO)) || {}).websiteId
  const websiteId = getQueryString('scope') || local_websiteId
  return websiteId
}

export function getSystemType() {
  return userInfoCache && userInfoCache.systemType
}

export function getUser() {
  return userInfoCache && userInfoCache.user
}

export function getGroup() {
  return userInfoCache && userInfoCache.group
}

export function getProject() {
  return userInfoCache && userInfoCache.project
}

export function getFunctionList() {
  return userInfoCache && userInfoCache.functionList
}

export function removeUserInfo() {
  userInfoCache = {}
  storage.remove(KEY_USERINFO)
}
